#include "connect.h"

#define _LISTEN_QUEUE_SIZE 16


int epollAdd(int epfd,int fd)
{
    struct epoll_event ev;
    ev.data.fd = fd;
    ev.events = EPOLLIN;
    int epoll_ctl_res = epoll_ctl(epfd,EPOLL_CTL_ADD,fd,&ev);
    ERROR_CHECK(epoll_ctl_res,-1,"epoll add error");
    return 0;
}

int epollDel(int epfd,int fd)
{
    int epoll_ctl_res = epoll_ctl(epfd,EPOLL_CTL_DEL,fd,NULL);
    ERROR_CHECK(epoll_ctl_res,-1,"epoll delete error");
    return 0;
}

int _tcp_init(const char* ip, const char* port){
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(sockfd, -1, "socket");
    int flag = 1;
    int res = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));

    ERROR_CHECK(res, -1, "setsockopt");
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(ip);
    addr.sin_port = htons(atoi(port));
    res = bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));
    ERROR_CHECK(res, -1, "bind");

    res = listen(sockfd, _LISTEN_QUEUE_SIZE);
    ERROR_CHECK(res, -1, "listen");

    //printf("tcp_init success.\n");// test only

    return sockfd;
}